package com.beta.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.beta.service.ISmsService;
import com.beta.service.ServiceException;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * Created by vector on 2016/11/21.
 */
@Service
public class SmsService implements ISmsService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${top.gateway.url}")
    private String serverUrl;

    @Value("${top.app.key}")
    private String appKey;

    @Value("${top.key.secret}")
    private String appSecret;

    @Value("${top.sms.free.sign.name}")
    private String signName;

    @Value("${sms.template.code}")
    private String templateCode;

    @Override
    public void sendConfirmCode(String phone, String code) {
        if (StringUtils.isBlank(phone)) {
            throw new ServiceException("E00100");
        }
        if (StringUtils.isBlank(code)) {
            throw new ServiceException("E00103");
        }

        try {
            send(phone, code);
        } catch (ApiException e) {
            throw new ServiceException("E00019");
        }
    }

    public void send(String phone, String code) throws ApiException {
        TaobaoClient client = new DefaultTaobaoClient(serverUrl, appKey, appSecret);
        AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
        req.setSmsType("normal");
        req.setSmsFreeSignName(signName);
        JSONObject paramJson = new JSONObject();
        paramJson.put("code", code);
        req.setSmsParamString(paramJson.toJSONString());
        req.setRecNum(phone);
        req.setSmsTemplateCode(templateCode);
        AlibabaAliqinFcSmsNumSendResponse rsp = client.execute(req);
        logger.debug("发送短信结果:{}", rsp.getBody());
    }

}
